package jmeter.test.functions;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.AbstractFunction;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class ApiSign extends AbstractFunction {

    private static final String KEY = "__apiSign";

    private static final List<String> desc = new LinkedList<>();

    private Object[] values;

    static {
        desc.add("用户app_id");
        desc.add("用户app_secret");
        desc.add("随机数");
        desc.add("时间戳");
    }

    public String execute(SampleResult sampleResult, Sampler sampler) throws InvalidVariableException {
        try {
            String appId = ((CompoundVariable) values[0]).execute().trim();
            String appSecret = ((CompoundVariable) values[1]).execute().trim();
            String nonce = ((CompoundVariable) values[2]).execute().trim();
            String time = ((CompoundVariable) values[3]).execute().trim();
            return md5(String.format("%s%s%s%s", appId, appSecret, nonce, time));
        } catch (Exception ex) {
            throw new InvalidVariableException(ex);
        }
    }

    public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
        checkParameterCount(parameters, 4); //检查参数的个数是否正确
        values = parameters.toArray(); //将值存入类变量中
    }

    public String getReferenceKey() {
        return KEY;
    }

    public List<String> getArgumentDesc() {
        return desc;
    }

    //写一个md5加密的方法
    private String md5(String plainText) {
        //定义一个字节数组
        byte[] secretBytes;
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            //对字符串进行加密
            md.update(plainText.getBytes());
            //获得加密后的数据
            secretBytes = md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        //将加密后的数据转换为16进制数字
        String md5code = new BigInteger(1, secretBytes).toString(16);
        // 如果生成数字未满32位，需要前面补0
        int count = 32 - md5code.length();
        for (int i = 0; i < count; i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }
}
